import 'package:flutter/material.dart';
import 'package:flutter_swipe_action_cell/core/cell.dart';

class ListOperationWidget extends StatefulWidget {
  const ListOperationWidget({super.key});

  @override
  State<StatefulWidget> createState() {
    return _ListOperationWidget();
  }
}

class _ListOperationWidget extends State<ListOperationWidget> {
  var items = List<String>.generate(10, (i) => "$i Item ");

  //数据源备份，在拖动时 会直接在数据源上修改 来影响UI变化，当拖动取消等情况，需要通过备份还原
  List<String> _dataListBackup = [];

  //手指覆盖的地方，即item被拖动时 底部的那个widget是否可见；
  bool _showItemWhenCovered = false;

  //当拖动覆盖到某个item上的时候，记录这个item的坐标
  int _willAcceptIndex = -1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          ListView.builder(
            shrinkWrap: true,
            itemCount: items.length,
            itemBuilder: (context, index) {
              var item = items[index];
              return SwipeActionCell(
                key: ValueKey(item),
                trailingActions: <SwipeAction>[
                  SwipeAction(
                      nestedAction: SwipeNestedAction(
                        title: "确认删除",
                      ),
                      title: "删除",
                      onTap: (CompletionHandler handler) async {
                        ///true 代表将会执行动画，等待动画结束才更新状态
                        await handler(true);
                        items.removeAt(index);
                        setState(() {});
                      },
                      color: Colors.red),
                  SwipeAction(
                    title: "置顶",
                    onTap: (CompletionHandler handler) async {
                      handler(false);
                    },
                    color: Colors.grey,
                  ),
                  SwipeAction(
                    title: "标记",
                    onTap: (CompletionHandler handler) async {
                      handler(false);
                    },
                    color: Colors.green,
                  ),
                ],
                child: Container(
                  color: Colors.white,
                  padding: const EdgeInsets.all(20.0),
                  child: Text(
                    item,
                    style: const TextStyle(fontSize: 12),
                  ),
                ),
              );
            },
          ),
          GridView.builder(
            shrinkWrap: true,
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 5,
              mainAxisSpacing: 10,
              crossAxisSpacing: 10,
            ),
            itemCount: items.length,
            itemBuilder: ((context, index) {
              return _gridItem(items[index], index);
            }),
          ),
        ],
      ),
    );
  }

  Widget _gridItem(item, index) {
    return LayoutBuilder(builder: (context, constraint) {
      //LongPressDraggable 长按拖动
      return Draggable(
        //当子child和feedback为同一个Widget时，可以设为false配合GlobalKey确保是同一个Widget 减少绘制
        ignoringFeedbackSemantics: false,
        data: item,
        //拖动的动态块Widget
        feedback: Material(
          //保证拖动的时候没有底色
          color: Colors.transparent,
          child: SizedBox(
            width: constraint.maxWidth,
            height: constraint.maxHeight,
            child: _itemBuild(item),
          ),
        ),
        //拖动时候，在原始位置展现的widget
        childWhenDragging: SizedBox(
          child: _showItemWhenCovered ? _itemBuild(item) : null,
        ),
        //开始拖拽
        onDragStarted: () {
          _dataListBackup = items.sublist(0);
          debugPrint("onDragStarted");
        },
        //拖拽失败回调
        onDraggableCanceled: (velocity, offset) {
          setState(() {
            _willAcceptIndex = -1;
            _showItemWhenCovered = false;
            items = _dataListBackup.sublist(0);
          });
          debugPrint("onDraggableCanceled:$velocity,$offset,$item");
        },
        //拖拽成功回调
        onDragCompleted: () {
          setState(() {
            _willAcceptIndex = -1;
            _showItemWhenCovered = false;
          });
          debugPrint("onDragCompleted");
        },
        //正常的Widget
        child: DragTarget(
          builder: (context, candidateData, rejectedData) {
            return _willAcceptIndex >= 0 && _willAcceptIndex == index
                ? Container()
                : _itemBuild(item);
          },
          //拖到该控件上时调用
          onWillAccept: (moveItem) {
            bool accept = moveItem != item;
            debugPrint("onWillAccept:$moveItem:$index");
            if (accept) {
              _willAcceptIndex = index;
              _showItemWhenCovered = true;
              items = _dataListBackup.sublist(0);
              setState(() {
                _changeItemAction(moveItem, item);
              });
            }
            return accept;
          },
          //放到该控件时调用--onWillAccept返回true 就会调用
          onAccept: (moveItem) {
            // _willAcceptIndex = index;
            // _showItemWhenCovered = true;
            // items = _dataListBackup.sublist(0);
            // setState(() {
            //   _changeItemAction(moveItem, item);
            // });
            // debugPrint("onAccept:$moveItem");
          },
          //没有放到该控件时调用
          onLeave: (moveItem) {
            _willAcceptIndex = -1;
            setState(() {
              _showItemWhenCovered = false;
              items = _dataListBackup.sublist(0);
            });
            debugPrint("onLeave:$moveItem");
          },
        ),
      );
    });
  }

  _changeItemAction(moveItem, toItem) {
    var toIndex = items.indexOf(toItem);
    items.remove(moveItem);
    items.insert(toIndex, moveItem);
  }

  Widget _itemBuild(item) {
    return Card(
      child: Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
        // child: Center(
        child: Text(item),
        // ),
      ),
    );
  }
}
